/*
 * @file com.mdlk.app.business.discover.diy.large.service.impl.WorkBenchImpl.java
 * @date 2021/6/21
 * @author lhz
 * @copyright 马丁洛克 Corporation 2021 版权所有
 * @version 0.0.1
 */
package com.sinux.generality.provider.pay.notify;

import com.alibaba.fastjson.JSONObject;
import com.sinux.generality.provider.pay.constants.NumberNum;
import com.sinux.generality.provider.pay.entity.GptPayOrder;
import com.sinux.generality.provider.pay.entity.GptPayPrepay;
import com.sinux.generality.provider.pay.factory.enums.NotifyStateEnums;
import com.sinux.generality.provider.pay.mapper.GptPayOrderMapper;
import com.sinux.generality.provider.pay.mapper.GptPayPrepayMapper;
import com.sinux.generality.provider.pay.service.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lhz
 * @version 0.0.1
 * @className NotifyBenchImpl
 * @describe 支付成功回调处理
 * @date 2021/10/25 9:13
 */
@Service
public class PayNotifyHandle implements PayNotifyBench {

    /****
     * @className PayNotifyHandle
     * @describe 支付成功回调通知
     * @author lhz
     * @date 2021/10/25 03:33
     * @version 0.0.1
     */
    @Resource
    private GptPayOrderMapper gptPayOrderMapper;

    @Resource
    private GptPayPrepayMapper gptPayPrepayMapper;
    @Resource
    private PayOrderService payOrderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notifyHandle(String json) {
        //处理业务
        JSONObject jsonObject = JSONObject.parseObject(json);
        //商户预支付订单号
        String outTradeNo = jsonObject.getString("out_trade_no");
        //微信订单号
        String transactionId = jsonObject.getString("transaction_id");
        //交易类型
        String tradeType = jsonObject.getString("trade_type");
        String successTime = jsonObject.getString("success_time");
        String tradeState = jsonObject.getString("trade_state");
        //处理支付成功
        if (tradeState.equals(NotifyStateEnums.SUCCESS.getCode())) {
            LocalDateTime parse = LocalDateTime.parse(successTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            //查询预支付单
            GptPayPrepay gptPayPrepay = gptPayPrepayMapper.selectById(outTradeNo);
            GptPayOrder payOrder = this.gptPayOrderMapper.selectById(gptPayPrepay.getPayOrderId());
            if (payOrder.getState()!= NumberNum.INT_1){
                return;
            }
            payOrder.setSuccessPrepayId(outTradeNo);
            payOrder.setSuccessTransactionId(transactionId);
            payOrder.setTradeType(tradeType);
            payOrder.setSuccessTime(parse);
            payOrder.setState(2);
            gptPayOrderMapper.updateById(payOrder);
            //处理业务订单状态
            payOrderService.handleBusinessState(payOrder, parse);
        }
    }
}

